    
	/***
	 * showOneSection: set up show/hide panel
	 * @param toshow
	 */
    function showOneSection(toshow) {
      var sections = [ 'main', 'approval', 'waiting' ];
      for (var i=0; i < sections.length; ++i) {
        var s = sections[i];
        var el = document.getElementById(s);
        if (s === toshow) {
          el.style.display = "block";
        } else {
          el.style.display = "none";
        }
      }
    }
    
    /***
     * fetchData: get data(DOM) from url, then call callback function
     * @param url
     * @param callback
     */
    function fetchData(url, callback) {
    	
      urlCurrent = url;
      callbackCurrent = callback;
      var params = {};
      //url = "https://sites.google.com/feeds/content/imlink.co.jp/dev_newsgadget";
      //url = "https://sites.google.com/feeds/activity/imlink.co.jp/dev_newsgadget/home";
      //url = "https://sites.google.com/feeds/content/imlink.co.jp/dev_newsgadget?parent=6299088910166870989";
      //url = "https://sites.google.com/feeds/content/imlink.co.jp/dev_newsgadget/?parent=6299088910166870989&kind=announcementspage";
      //url = "https://sites.google.com/feeds/content/imlink.co.jp/dev_newsgadget/?kind=webpage";
      //url = "https://sites.google.com/feeds/site/imlink.co.jp/dev_newsgadget";
      
      params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM;
      params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.OAUTH;
      params[gadgets.io.RequestParameters.OAUTH_SERVICE_NAME] = "google";
      params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;     

      gadgets.io.makeRequest(url, function (response) { 
        if (response.oauthApprovalUrl) {
          // Create the popup handler. The onOpen function is called when the user
          // opens the popup window. The onClose function is called when the popup
          // window is closed.
          var popup = shindig.oauth.popup({
            destination: response.oauthApprovalUrl,
            windowOptions: null,
            onOpen: function() { showOneSection('waiting'); },
            onClose: function() { 
            	debugger;
            	fetchData(urlCurrent,callbackCurrent);
            	showOneSection('main');
            }
          });
          // Use the popup handler to attach onclick handlers to UI elements.  The
          // createOpenerOnClick() function returns an onclick handler to open the
          // popup window.  The createApprovedOnClick function returns an onclick 
          // handler that will close the popup window and attempt to fetch the user's
          // data again.
          var personalize = document.getElementById('personalize');
          personalize.onclick = popup.createOpenerOnClick();
          var approvaldone = document.getElementById('approvaldone');
          approvaldone.onclick = popup.createApprovedOnClick();
          showOneSection('approval');
        } else if (response.data) {
         	callback(response.data);
         	showOneSection('main');
        } else {
          // The response.oauthError and response.oauthErrorText values may help debug
          // problems with your gadget.
          var main = document.getElementById('main');
          var err = document.createTextNode('OAuth error: ' +
            response.oauthError + ': ' + response.oauthErrorText);
          main.appendChild(err);
          showOneSection('main');
        }
      }, params);
    }
    
    /***
     * showPage: hander loaded data init
     * @param data
     */
    function showPage(data){
    	var lstEntry = getEntrys(data);
    	var entry = null;
    	listTabEntry = lstEntry;
    	for(var i = 0; i < lstEntry.length; i++) {
    		 tabs.addTab(lstEntry[i].title, {
    		 						callback:callbackSelectedTab
    		 						}); 
	    }
		allowSelected = true;
    	if(indexSelectedBackup!=0){
    		tabs.setSelectedTab(indexSelectedBackup);
    	}
    	
    	
    }
    
    /***
     * getEntrys: common parse data DOM to object Entry
     * @param data
     * @returns {Array}
     */
    function getEntrys(data){
    	var feed = data.childNodes[data.childNodes.length-1];
    	var lstEntry =[];
    	var count = 0;
   		for(var i = 0; i < feed.childNodes.length; i++) {
    		if(feed.childNodes[i].tagName == "entry"){
    			lstEntry[count] = getObjEntry(feed.childNodes[i]);
    			count ++;
			}
	      }
	     return lstEntry; 
    }
    
    /***
     * getObjEntry: common parse data DOM to object Entry
     * @param entry
     * @returns
     */
    function getObjEntry(entry){
    	if(typeof(entry)=="undefined" || typeof(entry.childNodes)=="undefined"){
    		return {};
    	}
    	var objEntry = {};
    	for(var i = 0; i < entry.childNodes.length; i++) {
    		var node = entry.childNodes[i];
    		if(node.tagName =="author") {
    			objEntry[node.tagName] = {name:"",email:"",fullname:""};
    			objEntry[node.tagName].name = typeof(node.childNodes[0].textContent)=="undefined" ? node.childNodes[0].text : node.childNodes[0].textContent;
    			objEntry[node.tagName].email = typeof(node.childNodes[1].textContent)=="undefined" ? node.childNodes[1].text : node.childNodes[1].textContent;
    			objEntry[node.tagName].fullname = typeof(node.textContent)=="undefined" ? node.text : node.textContent;
    		}else if(node.tagName =="link") {
    			if(typeof(objEntry["link"])== "undefined"){
    				objEntry["link"] = [];
    			}
    			var objLink = {};
    			for(var j = 0; j < node.attributes.length; j++) {
    				var attr = node.attributes[j];
    				objLink[attr.name] = attr.value;
    			}
    			objEntry["link"][objEntry["link"].length] =  objLink;
    		}
    		else
    			objEntry[node.tagName] = typeof(node.textContent)=="undefined" ? node.text : node.textContent;
	      }
	    return objEntry;
    }
    
    /***
     * callbackSelectedTab: handler selected tab to load data show grid
     * @param tabId
     */
	function callbackSelectedTab(tabId) {
		
		if(!allowSelected && indexSelectedBackup!=0) return ;
	  	// Get selected tab
	  	var selectedTab = tabs.getSelectedTab();
	  	var index = selectedTab.getIndex();
	  	var entry = listTabEntry[index];
	  	var id= entry.id;
	  	var arr = id.split("/");
	  	id = arr[arr.length-1];
	  	idEntryTabCurrent = id;
	  	
	  	// check has been loaded data
	  	var div_id = "div_content_" + idEntryTabCurrent;
	    var div_content = _gel(div_id);
	    if(div_content==null){
	  		div_content = document.createElement("div");
	    	div_content.id = div_id;
	    	div_content.innerHTML = "<center>loading...</center>";
	    	
	    	var element = selectedTab.getContentContainer();
	    	element.appendChild(div_content);
	    	
	    	var url = "https://sites.google.com/feeds/content/imlink.co.jp/dev_newsgadget/?parent="+ id +"&kind=announcement,comment";
	    	//var url = "http://www.google.com/m8/feeds/contacts/default/base?alt=json";
	  		fetchData(url,showAnouce);
	    }
	}
	
	/***
	 * showAnouce: handler loaded data 
	 * @param data
	 */
	function showAnouce(data){
		
		// get selected tab
		var selectedTab = tabs.getSelectedTab();
	  	var index = selectedTab.getIndex();
	  	var entry = listTabEntry[index];
		// set list announcement
		var lstEntry = getEntrys(data);
		lstEntry = exeSort(lstEntry,"title");
		entry["listSub"] = lstEntry ;
		renderListAnnouncement(lstEntry,"title","ASC");
	}
	
	/***
	 * renderListAnnouncement: render list entry to gridview
	 * @param lstEntry
	 * @param columnSort
	 * @param directSort
	 */
	function renderListAnnouncement(lstEntry,columnSort,directSort){
		
		if(typeof(columnSort)=="undefined") columnSort = "";
		if(typeof(directSort)=="undefined") directSort = "ASC";
		
		// set id 
		var idDivBody = "div_content_body_" + idEntryTabCurrent;
		var idDivHeader = "div_id_header_" + idEntryTabCurrent;
		var idHiddenSortName = "hidden_id_sort_" + idEntryTabCurrent;
		var idHiddenSortDirect = "hidden_id_sort_direct_" + idEntryTabCurrent;
		var htmlSort = "<span class='sort-asc'>&nbsp;&nbsp;&nbsp;</span>"
		if(directSort=="DESC"){
			htmlSort  = "<span class='sort-desc'>&nbsp;&nbsp;&nbsp;</span>" 
		}
		
		// general html header  
	 	var html = "";
	 	html += "<div class='div_tbody'style='height:auto !important; overflow: hidden !important;'>                   ";
	 	html += "<table class='tbList_css' style='width: auto' id='" + idDivHeader + "' cellspacing='0' cellpadding='0' >					";
	    html += "	<tr >                    ";
	    html += "		<th width='20px'></th>          ";
	    // �薼
	    html += "		<th width='250px' onclick='funcSort(\"title\")'>題名"
	    if(columnSort=="title")
	    	html += htmlSort ;
	    html += "</th>      ";
	    // �X�V��t
	    html += "		<th width='100px' onclick='funcSort(\"datetime\")'>更新日付"
		if(columnSort=="datetime")
		 	html += htmlSort ;
		html += "</th>      ";
		// ���e��
		html += "		<th width='100px' onclick='funcSort(\"user\")'>投稿者"
		if(columnSort=="user")
		 	html += htmlSort ;
		html += "</th>      ";
		// �T�}��
		html += "		<th >サマリ</th>    ";
	    
	    html += "	</tr>                   ";
	    html += "	</table>                   ";
	    html += "</div>                   ";
	    html += "<div class='div_tbody'>                   ";
	    html += "<table class='tbList_css' style='width: 100%;'  id='" + idDivBody + "' cellspacing='0' cellpadding='0' >					";
	    html += "	<tr >                    ";
	    html += "		<th width='20px' height='0px'> </th>          ";
	    html += "		<th width='250px'></th>      ";
	    html += "		<th width='100px'></th>   ";
	    html += "		<th width='100px'></th>       ";
	    html += "		<th ></th>    ";
	    html += "	</tr>                   ";
	    html += "	              ";
		   
	    // general html tbody
    	for(var i = 0; i < lstEntry.length; i++) {
    		var entry = lstEntry[i];
    		
    		var urlView = "";
    		for(var j = 0; j < entry.link.length; j++){
    			var objLink = entry.link[j];
    			if(objLink.rel=='alternate'){
    				urlView = objLink.href;
    				break;
    			}
    		}
    		
    		var author = entry.author.name;
    		var cssName = "css_le";
    		if(i%2==0) cssName = "css_chan";
    		
    		html += "	<tr class='"+cssName+"'>                    ";
    	    html += "		<td></td>           ";
    	    html += "		<td  align='left'><a target='_top' href='"+ urlView +"' >"+   writeSpan(entry.title,50)  + "</a></td>           ";
    	    html += "		<td align='center'>"+  DateUtil.strDateToString(entry.updated,"yyyy/MM/dd HH:mm") + "</td>           ";
    	    html += "		<td  align='center' title='"+ entry.author.fullname +"'>"+  author + "</td>           ";
    	    html += "		<td>"+  writeSpan(entry.content ,100)+ "</td>           ";
    	    html += "	</tr>                   ";
	    }
    	 html += "</table>                   ";
    	 html += "<input type='hidden' id='" + idHiddenSortName +"' value='"+ columnSort +"'>                   ";
    	 html += "<input type='hidden' id='" + idHiddenSortDirect +"' value='"+ directSort +"'>                   ";
    	 html += "</div>                   ";
    	
    	 // get div content
	    var idDivContent = "div_content_" + idEntryTabCurrent;
	    var divContent = _gel(idDivContent);
	    // set html into div content
	    divContent.innerHTML = html;
	    
	    // set width body, header
	    var divBody = _gel(idDivBody);
	    var divHeader = _gel(idDivHeader);
	    var widthTable = divBody.clientWidth;
	    divHeader.style.width = (widthTable +2) + "px";
	}
	
	/***
	 * funcSort: handler click to column name
	 * @param columnSort
	 */
	function funcSort(columnSort){
		// get id hidden sort
		var idHiddenSortName = "hidden_id_sort_" + idEntryTabCurrent;
		var idHiddenSortDirect = "hidden_id_sort_direct_" + idEntryTabCurrent;
		
		// get element hidden sort
		var hiddenSortName = _gel(idHiddenSortName);
		var hiddenSortDirect = _gel(idHiddenSortDirect);
		
		// get name column sort and direct sort current
		var oldSortName = hiddenSortName.value;
		var oldSortDirect = hiddenSortDirect.value;
		
		// get selected tab
		var selectedTab = tabs.getSelectedTab();
	  	var index = selectedTab.getIndex();
	  	var entry = listTabEntry[index];
	  	
	  	// get list entry
	  	var lstEntry = entry["listSub"];
	  	
	  	var directSort = "ASC";
	  	
		// if column sort is current
		if(columnSort == oldSortName){
			if(oldSortDirect=="ASC")
				directSort = "DESC";
			lstEntry.reverse();
		}else{
			// execute sort
			lstEntry = exeSort(lstEntry,columnSort);
		}
		// set into global variable
		entry["listSub"] = lstEntry;
		
		// render data to grid 
	  	renderListAnnouncement(lstEntry,columnSort,directSort);
	}
	
	/***
	 * execute sort ascending list 
	 */
	function exeSort(lstEntry, columnSort){
		if(columnSort=="title"){
			lstEntry.sort(function(a,b){
				return a.title > b.title;
			});
		}else if(columnSort=="datetime"){
			lstEntry.sort(function(a,b){
				return a.updated > b.updated;
			});
		}else if(columnSort=="user"){
			lstEntry.sort(function(a,b){
				return a.author.name > b.author.name;
			});
		}
		return lstEntry;
	}
	
	/***
	 * writeSpan: write string HTML span
	 * @param str
	 * @param lenbyte
	 * @returns {String}
	 */
	function writeSpan(str,lenbyte){
		return "<span title='" + str + "'>" + substr_utf8_bytes(str,0,lenbyte) + "</span";
	}

	/***
	 * refeshData: reload data 
	 */
    function refeshData(){
    	// get selected tab
		var selectedTab = tabs.getSelectedTab();
	  	var index = selectedTab.getIndex();
    	indexSelectedBackup = index;
    	allowSelected = false;
    	
    	clearTabs(tabs);
    	var url = "https://sites.google.com/feeds/content/imlink.co.jp/dev_newsgadget/?parent=6299088910166870989&kind=announcementspage";
    	fetchData(url,showPage);
    }
    
    /***
     * clearTabs: remove all tab
     * @param tabs
     */
    function clearTabs(tabs){
    	tabs.setSelectedTab(0);
    	var count  = tabs.getTabs().length;
    	for(var i=count-1; i>=0;i--){
    		tabs.removeTab(i);
    	}
    }